package com.etocrm.saas.lib.base.resource.exception;

import com.etocrm.saas.lib.base.common.exception.ErrorException;
import com.etocrm.saas.lib.base.common.result.Result;
import com.etocrm.saas.lib.base.common.result.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证异常处理
 */
@Slf4j
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.info("commence异常了:" + authException.getMessage());
        authException.printStackTrace();
        if(authException.getMessage().contains("Full authentication is required to access this resource")){
            resultError(response,ResultCodeEnum.USER_NOT_LOGIN_WARN);
        }else if(authException.getMessage().contains("Access token expired")){
            resultError(response,ResultCodeEnum.USER_TOKEN_TIMEOUT);
        }else if(authException.getMessage().contains("Cannot convert access token to JSON")){
            resultError(response,ResultCodeEnum.USER_TOKEN_ERROR);
        }
    }

    public void resultError(HttpServletResponse response,ResultCodeEnum codeEnum)throws IOException, ServletException{
        ObjectMapper objectMapper = new ObjectMapper();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(objectMapper.writeValueAsString(Result.fail(codeEnum)));
    }
}
